//
//  RealtimeDataModel.swift
//  AreaMeasureDevice
//
//  Created by iOS on 2021/5/13.
//  实时数据包

import Foundation
import MapKit

struct RealtimeDataModel {
    /// 数据编号
    var num:Int = 0
    /// 经度:度分秒秒秒 -> 度
    var longitude:Double = 0
    /// 纬度:度分秒秒秒 -> 度
    var latitude:Double = 0
    /// 测量面积(m²)
    var area:Float = 0
    /// 测量距离(cm)
    var distance:Float = 0
    /// 卫星数
    var statelliteNum:Int = 0
    /// 水平定位因子，放大 10 倍
    var hdop:Float = 0
    /// 速度(m/s)，放大 10 倍
    var speed:Float = 0
    /// 海拔高度(m)，放大 10 倍
    var altitude:Float = 0
    /// 电池电压(V)，放大 10000 倍
    var voltage:Float = 0
    /// crc 校验和
    var crc:String = ""

    var gpsLatitude:Double = 0
    var gpsLongitude:Double = 0

    init(hexStr:String) {
        if hexStr.count < 66 {
            return
        }
//        if hexStr[2..<10].contains("ffffffff") {
//            // 测量暂停
//            debugPrint("测量暂停")
//            return
//        }
        let lon_dd = Int(hexStr[10..<12], radix: 16)!
        let lon_mm = Int(hexStr[12..<14], radix: 16)!
        let lon_ss = Int(hexStr[14..<18], radix: 16)!
        let lon_sss = Int(hexStr[18..<20], radix: 16)!

        let lat_dd = Int(hexStr[20..<22], radix: 16)!
        let lat_mm = Int(hexStr[22..<24], radix: 16)!
        let lat_ss = Int(hexStr[24..<28], radix: 16)!
        let lat_sss = Int(hexStr[28..<30], radix: 16)!

        let longitude = getDuLonLatWith(dd: lon_dd, mm: lon_mm, ss: lon_ss, sss: lon_sss)
        let latitude = getDuLonLatWith(dd: lat_dd, mm: lat_mm, ss: lat_ss, sss: lat_sss)
        let coord2D = CLLocationCoordinate2D(latitude: latitude.roundTo(places: 8), longitude: longitude.roundTo(places: 8))
        self.gpsLatitude = coord2D.latitude
        self.gpsLongitude = coord2D.longitude

        let coordConvert = AMapCoordinateConvert(coord2D, .GPS)
        self.longitude = coordConvert.longitude
        self.latitude = coordConvert.latitude

        self.num = Int(hexStr[2..<10], radix: 16)!
        self.area = Float(UInt(hexStr[30..<38], radix: 16)!)
        self.distance = Float(UInt(hexStr[38..<46], radix: 16)!)
        self.statelliteNum = Int(UInt(hexStr[46..<48], radix: 16)!)
        self.hdop = Float(UInt(hexStr[48..<50], radix: 16)!) / 10
        self.speed = Float(UInt(hexStr[50..<54], radix: 16)!) / 10
        self.altitude = Float(UInt(hexStr[54..<58], radix: 16)!) / 10
        self.voltage = Float(UInt(hexStr[58..<62], radix: 16)!) / 10000
        self.crc = hexStr[62..<66]
    }

    

}


/// 经纬 度分秒秒秒 转 经纬 度
func getDuLonLatWith(dd:Int, mm:Int, ss:Int, sss:Int) -> Double {
    let number = (Double(dd) * 3600000 + Double(mm) * 60000 + Double(ss) * 10 + Double(sss) / 10) / 1000
    return number / 3600
}
